package com.dongdongshop.search.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dongdongshop.front.service.SearchService;
import com.dongdongshop.seller.pojo.TbItem;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Component
public class SearchServiceImpl implements SearchService {

    @Autowired
    private JestClient jestClient;

    @Override
    public List<TbItem> getGooodsAndGoodsDescByName(String str) throws IOException {

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        MatchQueryBuilder title = QueryBuilders.matchQuery("title",str);
        searchSourceBuilder.query(title);
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.field("title");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);
        Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex("dongdongshop").addType("item").build();
        List<TbItem> list = new ArrayList<>();
        /*try {*/
            SearchResult execute = jestClient.execute(search);
            List<SearchResult.Hit<TbItem, Void>> hits = execute.getHits(TbItem.class);
            for (SearchResult.Hit<TbItem, Void> hit : hits) {
                TbItem item = hit.source;
                Map<String,List<String>> highlight = hit.highlight;
                if (highlight != null){
                    String s = highlight.get("title").get(0);
                    item.setTitle(s);
                }
                list.add(item);
            }
       /* }catch (IOException e){
            e.printStackTrace();
        }*/

        return list;
    }
}
